package seed

import (
	"gorm.io/gorm"
	"wskyygyso/api/pkg/console"
	"wskyygyso/api/pkg/database"
)

type SeederFunc func(db *gorm.DB)

type Seeder struct {
	Func SeederFunc
	Name string
}

var seeders []Seeder

var orderedSeederNames []string

func Add(name string, fun SeederFunc) {
	seeders = append(seeders, Seeder{
		Name: name,
		Func: fun,
	})
}

func SetRunOrder(names []string) {
	orderedSeederNames = names
}

func GetSeeder(name string) Seeder {
	for _, seed := range seeders {
		if seed.Name == name {
			return seed
		}
	}
	return Seeder{}
}

func RunAll() {
	executed := make(map[string]string)
	for _, orderName := range orderedSeederNames {
		seed := GetSeeder(orderName)
		if len(seed.Name) > 0 {
			console.Warning("Running Odered Seeder: " + seed.Name)
			seed.Func(database.DB)
			executed[seed.Name] = seed.Name
		}
	}

	for _, seeder := range seeders {
		if _, ok := executed[seeder.Name]; !ok {
			console.Warning("Running  Seeder: " + seeder.Name)
			seeder.Func(database.DB)
			executed[seeder.Name] = seeder.Name
		}
	}
}

func RunSeeder(name string) {
	for _, seeder := range seeders {
		if name == seeder.Name {
			console.Warning("Running  Seeder: " + seeder.Name)
			seeder.Func(database.DB)
			break
		}
	}
}
